package pl.edu.agh.transstat.parsing;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import pl.edu.agh.transstat.simulation.Simulation;

public class ResultXmlParser extends DefaultHandler {

	private String path;
	private Simulation simulationsData;
	private Simulation dataTmp;
	//private ArrayList<String> paths;
	private String name;

	public ResultXmlParser (String path) {
		this.path = path;
		parseDocument();
	}

	private void parseDocument() {
		// get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {
			File file = new File(path);
			InputStream inputStream = new FileInputStream(file);
			Reader reader = new InputStreamReader(inputStream, "UTF-8");

			InputSource is = new InputSource(reader);
			is.setEncoding("UTF-8");
			// get a new instance of parser
			SAXParser sp = spf.newSAXParser();
			// parse the file and also register this class for call backs
			sp.parse(is, this);

		} catch (SAXException se) {
			se.printStackTrace();
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (IOException ie) {
			ie.printStackTrace();
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equalsIgnoreCase(ResultTags.SIM)) {
			dataTmp = new Simulation(new HashMap<String,List<Double>>());
		}
		
		if (qName.equalsIgnoreCase(ResultTags.MEASURE)) {
			name = attributes.getValue(ResultTags.NAME);	
			
		}
	}
	
	public void characters(char ch[], int start, int length) throws SAXException {
		Map<String,List<Double>> results = dataTmp.getResults();
		String s = new String(ch, start, length);
		s = s.trim();
		if (s.equals(""))
			return;
		double d = Double.parseDouble(s);
		List<Double> values;
		if (!results.containsKey(name))
			values = new ArrayList<Double>();
		else 
			values = results.get(name);
		values.add(d);
		results.put(name,values);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equals(ResultTags.SIM)) {
			simulationsData = dataTmp;
		}
		
	}

	public Simulation getData() {
		return simulationsData;
	}

}
